﻿using Microsoft.Extensions.DependencyInjection;
using Modules.Device.Repositories;
using PmSoft;
using PmSoft.Exceptions;

namespace Modules.Device
{
    [UseDI(ServiceLifetime.Scoped)]
    public class AppCheckinAuthService
    {
        private readonly AppCheckinAuthRepositoty appCheckinAuthRepositoty;

        public AppCheckinAuthService(AppCheckinAuthRepositoty appCheckinAuthRepositoty)
        {
            this.appCheckinAuthRepositoty = appCheckinAuthRepositoty;
        }

        /// <summary>
        /// </summary>
        /// <param name="query"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public IPagedList<AppCheckinAuth> GetAppCheckinAuths(AppCheckinAuthQuery query, int pageIndex, int pageSize)
        {
            return appCheckinAuthRepositoty.GetAppCheckinAuths(query, pageIndex, pageSize);
        }

        public IEnumerable<AppCheckinAuth> GetAppCheckinAuths(IEnumerable<int> ids)
        {
            return appCheckinAuthRepositoty.PopulateEntitiesByEntityIds(ids);
        }

        public void Create(AppCheckinAuth entity)
        {
            if (appCheckinAuthRepositoty.Exists(entity, null))
                throw new BusinessException($"当前参建企业已设置考勤权限");
            appCheckinAuthRepositoty.Insert(entity);
        }

        public void Update(AppCheckinAuth entity)
        {
            if (appCheckinAuthRepositoty.Exists(entity, entity.Id))
                throw new BusinessException($"当前参建企业已设置考勤权限");
            appCheckinAuthRepositoty.Update(entity);
        }

        public AppCheckinAuth? GetAppCheckinAuthByProjectIdAndCorpId(int projectId, int corpId)
        {
            return appCheckinAuthRepositoty.GetAppCheckinAuthsByProjectId(projectId).FirstOrDefault(a => a.CorpId == corpId);
        }

        public IEnumerable<AppCheckinAuth> GetAppCheckinAuthsByProjectId(int projectId)
        {
            return appCheckinAuthRepositoty.GetAppCheckinAuthsByProjectId(projectId);
        }

        /// <summary>
        /// </summary>
        /// <param name="id"></param>
        public void Delete(int id)
        {
            appCheckinAuthRepositoty.DeleteByEntityId(id);
        }

        /// <summary>
        /// </summary>
        /// <param name="ids"></param>
        public void Deleted(IEnumerable<int> ids)
        {
            foreach (int id in ids)
            {
                Delete(id);
            }
        }

        /// <summary>
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public AppCheckinAuth? Get(int id)
        {
            return appCheckinAuthRepositoty.Get(id);
        }
    }
}